package com.huihui.datamanager;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.huihui.bean.HistoryBean;
import com.huihui.network.pojo.UserInfo;
import com.huihui.utils.Contants;

/**
 * Created by daimeng on 2018/8/9 14:34.
 */

public class AppManager {

    private static AppManager instance = null;
    private static Context mContext;
    private static String mToken;

    private AppManager(Context context) {
        mContext = context;
    }

    private static DataCache mDataCache = null;
    private static Gson mGson = new Gson();

    /**
     * 获取Gson解析器
     *
     * @return
     */
    public static Gson getGson() {
        return mGson;
    }

//    ClientSystemConfig tempClientSystemConfig = AppManager.getGson().fromJson(new JSONObject(map).toString(), ClientSystemConfig.class);

    /**
     * 获取数据存储器
     * @return
     */
    public static DataCache getDataCache() {
        if (mDataCache == null) {
            if(mContext!=null)
                mDataCache = DataCache.get(mContext.getFilesDir());
            return mDataCache;
        } else {
            return mDataCache;
        }
    }

    public static AppManager getInstance() {
        return instance;
    }

    public static void initAppManager(Context context) {
        if (instance == null) {
            instance = new AppManager(context);
        }
    }

    public static void setToken(String token){
        mToken = token;
        getDataCache().put(Contants.TOKEN,token);
    }

    public static String getToken(){
        if(!TextUtils.isEmpty(mToken)){
            return mToken;
        }else{
            return getDataCache().getAsString(Contants.TOKEN);
        }
    }

    public static void deleteToken(){
        getDataCache().remove(Contants.TOKEN);
    }

    public static void setUserInfo(UserInfo userInfo){
        getDataCache().put(Contants.USERINFO, getGson().toJson(userInfo));
    }

    public static UserInfo getUserInfo(){
        String str = getDataCache().getAsString(Contants.USERINFO);
        UserInfo userInfo = AppManager.getGson().fromJson(str,UserInfo.class);
        return userInfo;
    }

    public static void deleteUserInfo(){
        getDataCache().remove(Contants.USERINFO);
    }

    public  static void setHistory(HistoryBean history){
        getDataCache().put(Contants.HISTORY, getGson().toJson(history));
    }

    public static HistoryBean getHistory(){
        String str = getDataCache().getAsString(Contants.HISTORY);
        HistoryBean historyBean = AppManager.getGson().fromJson(str,HistoryBean.class);
        return historyBean;
    }

    public static void deleteHisttory(){
        getDataCache().remove(Contants.HISTORY);
    }

}
